package com.exception.handler;

import com.exception.exception.MyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 这种handler优先级最高？，将会忽略自定义的异常处理（MyExceptionHandler）
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({Exception.class})
    protected ModelAndView globalExceptionHandler(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        ModelAndView mv = new ModelAndView();
        try {
            if (e instanceof MyException) {
                MyException ex = (MyException) e;
                String message = ex.getCode() + ex.getMesssage();
                response.sendError(ex.getHttpStatus().value(), message);
                mv.addObject(message);
            } else {
                System.out.println("not my exception");
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
                mv.addObject(e.getMessage());
            }
        } catch (IOException exception) {
            System.out.println(exception.getMessage());
        }
        return mv;
    }

    @ExceptionHandler({MyException.class})
    protected ModelAndView myExceptionHandler(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        ModelAndView mv = new ModelAndView();
        try {
            if (e instanceof MyException) {
                MyException ex = (MyException) e;
                String message = ex.getCode() + ex.getMesssage();
                response.sendError(ex.getHttpStatus().value(), message);
                mv.addObject(message);
            } else {
                System.out.println("not my exception");
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
                mv.addObject(e.getMessage());
            }
        } catch (IOException exception) {
            System.out.println(exception.getMessage());
        }
        return mv;
    }
}
